#include <iostream>
#include "Socket.hpp"
#include "EventLoop.hpp"

class Acceptor
{
private:
    Sock _socket;     // 监听套接字
    EventLoop *_loop; // 用于对监听套接字进行事件监控
    Channel _channel; // 用于对监听套接字进行事件管理

    using AcceptCallBack = std::function<void(int)>;
    AcceptCallBack _accept_callback;

private:
    /*监听套接字的读事件回调处理函数--获取新连接，调用回调函数进行新连接处理*/
    void HandleRead()
    {
        int newfd = _socket.Accept();
        if (newfd < 0)
            return;
        if (_accept_callback)
            _accept_callback(newfd);
    }
    int CreateServer(int port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }

public:
    
    Acceptor(EventLoop *loop, int port) : _socket(CreateServer(port)), _loop(loop), _channel(_socket.Fd(), loop)
    {
        _channel.SetReadCallBack(std::bind(&Acceptor::HandleRead, this));
    }
    void SetAcceptCallBack(const AcceptCallBack &cb) { _accept_callback = cb; }
    void Listen() { _channel.EnableRead(); }
};